<?php

namespace Handler;

use Model\User;
use GatewayWorker\Lib\Db;
use Extension\Tools;
use Config\Cfg;
use Workerman\Lib\Timer;

class UserHandler {
	/**
	 * 单例
	 *
	 * @var UserHandler
	 */
	private static $m_Instance;
	/**
	 * 在线用户
	 *
	 * @var User[]
	 */
	private $m_Users;
	/**
	 * 当前用户数
	 *
	 * @var int
	 */
	private $m_CurUserCount;
	/**
	 * 历史最高用户数
	 *
	 * @var unknown
	 */
	private $m_MaxUserCount;
	/**
	 *
	 * @var \Req_sfslobby
	 */
	private $m_ReqSFS;
	/**
	 * 构造函数
	 */
	private function __construct() {
		Timer::add ( 1, array (
				$this,
				'mb_TimeTask' 
		), array (), true );
		$this->m_Users = array ();
		$this->m_CurUserCount = 0;
		$this->m_MaxUserCount = 0;
		$this->m_ReqSFS = new \Req_sfslobby ();
	}
	/**
	 * 复制方法
	 */
	private function __clone() {
	}
	/**
	 * 获取单例
	 *
	 * @return UserHandler
	 */
	public static function mb_GetInstance() {
		if (! (self::$m_Instance instanceof self)) {
			self::$m_Instance = new self ();
		}
		return self::$m_Instance;
	}
	/**
	 * 添加一个User
	 *
	 * @param User $user        	
	 */
	public function mb_AddUser($user) {
		$this->m_Users [$user->m_Name] = $user;
		
		$this->m_CurUserCount ++;
		if ($this->m_MaxUserCount < $this->m_CurUserCount)
			$this->m_MaxUserCount = $this->m_CurUserCount;
	}
	/**
	 * 移除一个User
	 *
	 * @param User $user        	
	 */
	public function mb_RemoveUser($name) {
		if (isset ( $this->m_Users [$name] )) {
			$user = $this->m_Users [$name];
			// 更新一个用户信息
			Db::instance ( 'lobby' )->update ( 'userinfo' )->cols ( $user->mb_Logout () )->where ( "name='$name'" )->query ();
			// 写入数据日志
			$dataLogs = $user->mb_GetDataLogs ();
			for($i = 0; $i < count ( $dataLogs ); $i ++) {
				Db::instance ( 'lobby' )->insert ( 'datalog' )->cols ( $dataLogs [$i] )->query ();
			}
			// 写入登录日志
			$loginLogs = $user->mb_GetLoginLog ();
			for($i = 0; $i < count ( $loginLogs ); $i ++) {
				Db::instance ( 'lobby' )->insert ( 'loginlog' )->cols ( $loginLogs [$i] )->query ();
			}
			// 移除一个用户实例
			unset ( $this->m_Users [$name] );
			$this->m_CurUserCount --;
		}
	}
	/**
	 * 断线退出
	 *
	 * @param string $clientId        	
	 */
	public function mb_OnClose($clientId) {
		$user = $this->mb_GetUserForClientId ( $clientId );
		if (isset ( $user )) {
			$name = $user->m_Name;
			if ($user->m_CurStatus == User::STATUS_GAME) {
				
				$sfsData = TPHandler::mb_GetInstance ()->mb_QueryDataToTP ( $user->m_Name );
				if ($sfsData->state == false) {
					$this->mb_OutHttpMessage ( $clientId, ErrCode_Toast, $sfsData->msg );
					return;
				}
				$uData = json_decode ( $sfsData->data );
				$user->m_Coin = $uData->coin;
				$user->mb_ExitGame ();
				LobbyHandler::mb_GetInstance ()->mb_StatisticsOnlineUsers ( $user->m_GameId, $user->m_Name, false );
			}
			
			$this->mb_RemoveUser ( $name );
			echo "$name Logout For Disconnect!\n";
		}
	}
	public function mb_GetAllUsers() {
		return $this->m_Users;
	}
	/**
	 * 根据账号获取一个User
	 *
	 * @param string $name        	
	 * @return User|NULL
	 */
	public function mb_GetUserForName($name) {
		if (isset ( $this->m_Users [$name] ))
			return $this->m_Users [$name];
		else
			return null;
	}
	/**
	 * 根据Token获取一个User
	 *
	 * @param string $token        	
	 * @return User|NULL
	 */
	public function mb_GetUserForToken($token) {
		if ($this->m_Users == null) {
			return null;
		} else {
			foreach ( $this->m_Users as $user ) {
				if ($user->m_Token == $token)
					return $user;
			}
			return null;
		}
	}
	/**
	 * 根据clientId获取一个User
	 *
	 * @param string $clientId        	
	 * @return User|NULL
	 */
	public function mb_GetUserForClientId($clientId) {
		if ($this->m_Users == null) {
			return null;
		} else {
			foreach ( $this->m_Users as $user ) {
				if ($user->m_ClientId == $clientId)
					return $user;
			}
			return null;
		}
	}
	/**
	 * 根据OPENID获取一个User
	 *
	 * @param unknown $openId        	
	 * @return NULL|\Model\User
	 */
	public function mb_GetUserForOpenId($openId) {
		if ($this->m_Users == null) {
			return null;
		} else {
			foreach ( $this->m_Users as $user ) {
				if ($user->m_openId == $openId)
					return $user;
			}
			return null;
		}
	}
	/**
	 * 根据手机号码获取一个User
	 *
	 * @param unknown $phone        	
	 * @return NULL|\Model\User
	 */
	public function mb_GetUserForPhone($phone) {
		if ($this->m_Users == null) {
			return null;
		} else {
			foreach ( $this->m_Users as $user ) {
				if ($user->m_Phone == $phone)
					return $user;
			}
			return null;
		}
	}
	/**
	 * 根据OPENID从数据库中获取用户数据
	 *
	 * @param unknown $openId        	
	 * @return array
	 */
	public function mb_GetUserForOpenIdFromDB($openId) {
		return Db::instance ( 'lobby' )->select ( '*' )->from ( 'userinfo' )->where ( "openid='$openId'" )->row ();
	}
	/**
	 * 根据NAME从数据库中获取用户数据
	 *
	 * @param unknown $name        	
	 * @return array
	 */
	public function mb_GetUserForNameFromDB($name) {
		return Db::instance ( 'lobby' )->select ( '*' )->from ( 'userinfo' )->where ( "BINARY name='$name'" )->row ();
	}
	/**
	 * 根据手机号码从数据库中获取用户数据
	 *
	 * @param unknown $phone        	
	 * @return array
	 */
	public function mb_GetUserForPhoneFromDB($phone) {
		return Db::instance ( 'lobby' )->select ( '*' )->from ( 'userinfo' )->where ( "phone='$phone'" )->row ();
	}
	/**
	 * 根据Token从数据库中获取用户数据
	 *
	 * @param unknown $token        	
	 * @return array
	 */
	public function mb_GetUserForTokenFromDB($token) {
		return Db::instance ( 'lobby' )->select ( '*' )->from ( 'userinfo' )->where ( "token='$token'" )->row ();
	}
	/**
	 * 根据账号密码从数据库中获取用户数据
	 *
	 * @param unknown $name        	
	 * @param unknown $encPass        	
	 * @return array
	 */
	public function mb_GetUserForNamePassFromDB($name, $encPass) {
		return Db::instance ( 'lobby' )->select ( '*' )->from ( 'userinfo' )->where ( array (
				'name' => $name,
				'encpass' => $encPass 
		) )->row ();
	}
	/**
	 * 添加一个微信用户数据到数据库
	 *
	 * @param unknown $nick        	
	 * @param unknown $head        	
	 * @param unknown $sex        	
	 * @param unknown $openId        	
	 * @param unknown $unionId        	
	 * @return mixed|NULL|string|array|number
	 */
	public function mb_AddWeChatUserToDB($name, $nick, $head, $sex, $openId, $unionId) {
		$data = array (
				'name' => $name,
				'nick' => $nick,
				'head' => $head,
				'sex' => $sex,
				'openid' => $openId,
				'unionid' => $unionId,
				'registdate' => Tools::mb_GetCurDateTime () 
		);
		return Db::instance ( 'lobby' )->insert ( 'userinfo' )->cols ( $data )->query ();
	}
	/**
	 * 添加一个手机用户数据到数据库
	 *
	 * @param unknown $name        	
	 * @param unknown $nick        	
	 * @param unknown $head        	
	 * @param unknown $sex        	
	 * @param unknown $phone        	
	 * @return mixed|NULL|string|array|number
	 */
	public function mb_AddPhoneUserToDB($name, $phone) {
		$data = array (
				'name' => $name,
				'nick' => $name,
				'head' => Cfg::DF_HEAD,
				'sex' => 1,
				'phone' => $phone,
				'registdate' => Tools::mb_GetCurDateTime () 
		);
		return Db::instance ( 'lobby' )->insert ( 'userinfo' )->cols ( $data )->query ();
	}
	/**
	 * 添加一个用户数据到数据库
	 *
	 * @param unknown $name        	
	 * @param unknown $basePass        	
	 * @param unknown $encPass        	
	 */
	public function mb_AddNameUserToDB($name, $basePass, $encPass, $phone) {
		$data = array (
				'name' => $name,
				'basepass' => $basePass,
				'encpass' => $encPass,
				'registdate' => Tools::mb_GetCurDateTime (),
				'phone' => $phone 
		);
		return Db::instance ( 'lobby' )->insert ( 'userinfo' )->cols ( $data )->query ();
	}
	/**
	 * 更新用户数据到数据库
	 *
	 * @param unknown $name        	
	 * @param array $data        	
	 * @return mixed|NULL|string|array|number
	 */
	public function mb_UpdateUserDataToDB($name, $data) {
		return Db::instance ( 'lobby' )->update ( 'userinfo' )->cols ( $data )->where ( "name='$name'" )->query ();
	}
	/**
	 * 删除用户记录
	 *
	 * @param unknown $name        	
	 * @return mixed|NULL|string|array|number
	 */
	public function mb_DeleteUserToDB($name) {
		return Db::instance ( 'lobby' )->delete ( 'userinfo' )->where ( "name='$name'" )->query ();
	}
	/**
	 * 获取用户状态
	 *
	 * @return number[]|\Handler\unknown[]
	 */
	public function mb_GetUserStatus() {
		return array (
				'cur' => $this->m_CurUserCount,
				'max' => $this->m_MaxUserCount 
		);
	}
	/**
	 * 定时任务（每一秒执行一次）
	 */
	public function mb_TimeTask() {
		$this->mb_ScanUserHeartBeat ();
	}
	/**
	 * 从sfs中更新用户数据
	 *
	 * @param User $user        	
	 */
	public function mb_UpdateUserDataFromSFS($user) {
		// $sfsData = SFSHandler::mb_GetInstance ()->mb_QueryDataToSFS ( $user->m_Name );
		$sfsData = TPHandler::mb_GetInstance ()->mb_QueryDataToTP ( $user->m_Name );
		if ($sfsData->state == false) {
			return;
		}
		$uData = json_decode ( $sfsData->data );
		$user->m_Coin = ( int ) $uData->coin;
		// $user->m_Coin = ( int ) $sfsData->data [0]->coins;
	}
	/**
	 * 扫描掉线用户
	 */
	private function mb_ScanUserHeartBeat() {
		if ($this->m_Users == null)
			return;
		if (count ( $this->m_Users ) == 0)
			return;
		foreach ( $this->m_Users as $user ) {
			if ((time () - $user->m_HeartBeat) > 60) {
				$this->mb_RemoveUser ( $user->m_Name );
			}
		}
	}
}